package com.wl.dzt.sys.core.dao.curd.mssql;

import com.wl.dzt.sys.core.dao.curd.mysql.SelectSqlBuilderForMysql;
import com.wl.dzt.sys.core.dao.mate.DataMateBase;
import com.wl.dzt.sys.core.dao.mate.DataMateColumn;
import com.wl.dzt.sys.core.dao.select.SelectMate;
import com.wl.dzt.sys.core.dao.select.SelectSqlBuilder;
import com.wl.dzt.sys.core.dao.select.order.Sort;
import com.wl.dzt.sys.util.CollectionUtil;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;


/**
 * @author wl_code@163.com
 * @version 1.0
 * @date 2018/7/5/005
 * @description microsoft sql server查询构建器
 */
@Component
public class SelectSqlBuilderForMssql extends SelectSqlBuilderForMysql implements SelectSqlBuilder {


    /**
     * 构建microsoft sql serve分页
     *
     * @param selectMate
     * @param start
     * @param limit
     */
    public void builderPage(SelectMate selectMate, Integer start, Integer limit) {
        start = start + 1;
        limit = start + limit - 1;
        selectMate.setPageSql(limit > 0 ? (" SELECT temp.* FROM  ( %s ) temp  WHERE tempPageIndexRowNumber BETWEEN " + start
                + " AND " + limit + " ") : "");
    }


    /**
     * 构建microsoft sql serve查询字段
     *
     * @param selectMate
     * @param clazz
     * @param fields
     */
    public void builderFields(SelectMate selectMate, Class<?> clazz, Set<String> fields) {
        fields.addAll(selectMate.getRefIds());
        List<String> sqlFields = new ArrayList<>();
        // String key = selectMate.getBaseTable() + ".id";
        String key = "getdate()";
        sqlFields.add(" row_number () OVER (ORDER BY " + key + ") as tempPageIndexRowNumber ");
        fields.forEach(field -> {
            DataMateColumn column = DataMateBase.getTable(clazz).getColumn(field);
            if (column != null) {
                String asSql = column.asFieldName(field) + " as " + field.replaceAll("[.]", "_");
                sqlFields.add(asSql);
            }
        });
        selectMate.setFieldSql(CollectionUtil.join(sqlFields, ","));
    }


    /**
     * microsoft sql serve排序
     *
     * @param selectMate
     * @param clazz
     * @param sorts
     */
    public void builderOrder(SelectMate selectMate, Class<?> clazz, List<Sort> sorts) {
        if (!sorts.isEmpty()) {
            List<String> allOrders = new ArrayList<>();
            sorts.forEach(sort -> {
                String field = sort.getField();
                // DataMateColumn column =
                // DataMateBase.getTable(clazz).getColumn(field);
                allOrders.add(String.format(" %s  %s ", field.replace(".", "_"), sort.getType()));
            });
            selectMate.setOrderSql(String.format(" order by  %s ", CollectionUtil.join(allOrders, ",")));
        }
    }
}
